package edu.cuhk.cs.bookstore.util;

import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import aws.*;

public class StringUtil {

	public static Date parseDateFormat(String in) {
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			return format.parse(in);
		} catch (ParseException e) {
			//e.printStackTrace();
		}
		return null;
	}
	
	public static String join(Object[] array, String separator) {
	      if (array == null) {
	          return "";
	      }
	      return join(array, separator, 0, array.length);
	  }
	
	public static String getImageURL(Image image) {
		if (image != null) {
			return image.getURL();
		}
		return "img/noimage.jpg";
	}
	
	public static String getImageWidth(Image image) {
		if (image != null) {
			return String.valueOf(image.getWidth().get_value());
		}
		return "";
	}
	public static String getImageHeight(Image image) {
		if (image != null) {
			return String.valueOf(image.getHeight().get_value());
		}
		return "";
	}
	
	public static String getFormattedPrice(Price price) {
		if (price != null) {
			return price.getFormattedPrice();
		}
		return "";
	}
	
	  public static String join(Object[] array, String separator, int startIndex, int endIndex) {
	      if (array == null) {
	          return null;
	      }
	      if (separator == null) {
	          separator = "";
	      }

	      int bufSize = (endIndex - startIndex);
	      if (bufSize <= 0) {
	          return "";
	      }

	      bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length())
	                      + separator.length());

	      StringBuffer buf = new StringBuffer(bufSize);

	      for (int i = startIndex; i < endIndex; i++) {
	          if (i > startIndex) {
	              buf.append(separator);
	          }
	          if (array[i] != null) {
	              buf.append(array[i]);
	          }
	      }
	      return buf.toString();
	  }
	  
	  public static String encodeURI(String value) {
		  try {
			  if (value != null) {
				  value = URLEncoder.encode(value, "UTF-8");
				  //value = value.replace("+", "%20");
			  }
		  }
		  catch(Exception e) {
			 // e.printStackTrace();
		  }
		  return value;
	  }

	public static String formatCriteria(String value) {
		  try {
			  if (value != null) {
				  value = value.trim();
				  value.replaceAll(" ", "*");
				  value += "*";
				  //value = value.replace("+", "%20");
			  }
		  }
		  catch(Exception e) {
			 // e.printStackTrace();
		  }
		  return value;
	}
}
